import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import utils from 'src/common/utils';
import { system_wx_user, system_wx_user_2, video_SubAppId_List, wx_appid } from 'src/setting';
import { In, Repository, UpdateResult } from 'typeorm';
import { Video } from '../video/video.entity';
import { WxUser } from './wxUser.entity';
import { InternetCelebrity } from '../internetCelebrity/internetCelebrity.entity';
import { UserSetting } from '../userSetting/userSetting.entity';
import SMS from 'src/common/sms';
import { WxUserOpenId } from '../wxUserOpenId/wxUserOpenId.entity';
import { UnConcern } from '../unconcern/unconcern.entity';
import { getQueryVideoField, videoFields } from 'src/common/sql/video';
import { InternetCelebrityGroup } from '../internetCelebrityGroup/internetCelebrityGroup.entity';
import { RedisCacheService } from '../redisCache/redisCache.service';

@Injectable()
export class WxUserService {
  constructor(
    @InjectRepository(WxUser)
    private wxUserRepository: Repository<WxUser>,
    @InjectRepository(UserSetting)
    private userSettingRepository: Repository<UserSetting>,
    @InjectRepository(WxUserOpenId)
    private wxUserOpenIdRepository: Repository<WxUserOpenId>,
    @InjectRepository(UnConcern)
    private unConcernRepository: Repository<UnConcern>,
    @InjectRepository(InternetCelebrityGroup)
    private internetCelebrityGroupRepository: Repository<InternetCelebrityGroup>,
    private readonly redisCacheService: RedisCacheService,
  ) {}

  batchPlatform(platformList){
    platformList.map(e => {
      for(let key in e){
        if(e[key] === undefined || e[key] === null){
          e[key] = ''
        }
      }
    })
    platformList = platformList.filter(e => {
      return e.platform || e.account || e.avatar_img || e.ic_name || e.img
    })
    return platformList
  }

  async findByName(wx_user: string, keyword: string, skip: number, take: number){
      // where internet_celebrity_group.type = 2 and d.name like ? and d.openid != ? and d.openid != 'oGCIM6xIWkOgZ_QxejB3TrMl1-MQ' and d.openid in (
        //认证网红
    let dataList = await this.wxUserRepository.query(`select d.id,d.name,d.openid,b.id as concern_id,
      d.avatar_img,d.id_card, internet_celebrity_group.id as ic_group
      from wx_user d
      left join internet_celebrity_group on internet_celebrity_group.wx_user = d.openid and internet_celebrity_group.type = 2
      left join concern b on b.concern_wx_user_id = d.id and b.wx_user = ?
      where (d.id_card = ? or d.name like ?) and d.openid != ? and d.openid in (
        select a.wx_user from user_setting a where a.key = 'overseas' and a.value = 1
      ) and d.openid in (
        select wx_user from video
        where video.profit_type = 1 and video.check = 1 and video.original = 1 and video.overseas = 1
      )
      limit ?,?
    `,[wx_user, utils.filteremoji(keyword), `%${utils.filteremoji(keyword)}%`, wx_user, skip, take])

    console.log(dataList,'dataList')

    //虚拟网红
    //1、视频库tk
    let virtually = await this.wxUserRepository.query(`
      select a.id,
      (
        select name from internet_celebrity where ic_group = a.id
        order by id ASC
        limit 0,1
        ) as name
      ,b.id as concern_id,(
      select avatar_img from internet_celebrity where ic_group = a.id
      order by id ASC
      limit 0,1
      ) as avatar_img,a.id_card, a.id as ic_group
      from internet_celebrity_group a
      inner join platform on platform.ic_group = a.id
      left join concern b on b.concern_ic_group = a.id and b.wx_user = ?
      where (
        (
          a.type = 0 and (
            platform.platform in (select setting.value from setting where setting.key = 'level3')
            or (select count(1) from platform where platform.platform != '' and platform.ic_group = a.id) = 0
          )
        )
        or a.type = 3
      )
      and (
        a.id in (
          select ic_group from internet_celebrity where name like ?
        ) or a.id_card = ?
      )
      and a.delete_tag = 0 and a.id in (
        select ic_group from video
          where (
            -- 提问视频，进入网红主页
            (
              video.original = 0 and video.in_ic = 1
            )
            -- 非认证作品，进入网红主页
            or (
              video.overseas = 3 and video.in_ic = 1 and video.profit_type = 1 and video.original = 1
            )
            -- 视频库视频
            or (
              video.overseas = 0 and video.type = 0 and (video.in_ic is null or video.in_ic = 1) and video.original = 1
            )
          )
      )
      limit ?,?
    `,[wx_user, `%${utils.filteremoji(keyword)}%`, utils.filteremoji(keyword), skip, take])


    let total = await this.wxUserRepository.query(`
      select count(1) as total
      from wx_user d
      where (d.id_card = ? or d.name like ?) and d.openid != ? and d.openid in (
        select a.wx_user from user_setting a where a.key = 'overseas' and a.value = 1
      ) and d.openid in (
        select wx_user from video
        where video.profit_type = 1 and video.check = 1 and video.original = 1
      )
    `,[utils.filteremoji(keyword), `%${utils.filteremoji(keyword)}%`, wx_user])

    let total_virtually = await this.wxUserRepository.query(`
      select count(1) as total
      from internet_celebrity_group a
      inner join platform on platform.ic_group = a.id
      where (
        (
          a.type = 0 and (
            platform.platform in (select setting.value from setting where setting.key = 'level3')
            or (select count(1) from platform where platform.platform != '' and platform.ic_group = a.id) = 0
          )
        )
        or a.type = 3
      )
      and (
        a.id in (
          select ic_group from internet_celebrity where name like ?
        ) or a.id_card = ?
      )
      and a.delete_tag = 0 and a.id in (
        select ic_group from video
          where (
            -- 提问视频，进入网红主页
            (
              video.original = 0 and video.in_ic = 1
            )
            -- 非认证作品，进入网红主页
            or (
              video.overseas = 3 and video.in_ic = 1 and video.profit_type = 1 and video.original = 1
            )
            -- 视频库视频
            or (
              video.overseas = 0 and video.type = 0 and (video.in_ic is null or video.in_ic = 1) and video.original = 1
            )
          )
      )
    `,[`%${utils.filteremoji(keyword)}%`, utils.filteremoji(keyword)])

    
    //查询平台信息
    let platformList = await this.wxUserRepository.query(`
      select platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
          'virtually_ic_info' as type
          from internet_celebrity_group
          inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
          inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
          inner join platform on platform.ic_group = internet_celebrity_group.id
          where (
            (
              (
                internet_celebrity_group.type = 0 and (
                  platform.platform in (select setting.value from setting where setting.key = 'level3')
                  or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                )
              )
              or internet_celebrity_group.type = 3
            )
            and(internet_celebrity_group.id_card = ? or internet_celebrity.name like ?)
          )
      union
      select distinct platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
        'local_ic_info' as type
      from wx_user a
      inner join internet_celebrity_group on internet_celebrity_group.wx_user = a.openid and internet_celebrity_group.type = 2
      inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
      inner join platform on platform.ic_group = internet_celebrity_group.id and platform.id = internet_celebrity.platform and platform.platform != '' and platform.platform is not null
      where internet_celebrity_group.type = 2 and a.openid in (
              select a.wx_user from user_setting a where a.key = 'overseas' and a.value = 1
            ) and (a.id_card = ? or a.name like ?)
    `,[utils.filteremoji(keyword), `%${utils.filteremoji(keyword)}%`, utils.filteremoji(keyword), `%${utils.filteremoji(keyword)}%`])

    dataList.filter(e => e.ic_group).map(e => {
      e.platformList = this.batchPlatform(platformList.filter(c => c.id == e.ic_group))
    })
    dataList.filter(e => e.openid == wx_user).map(e => {
      e.disabled_concern = true
      delete e.openid
    })
    virtually.map(e => {
      e.overseas = 3
      e.platformList = this.batchPlatform(platformList.filter(c => c.id == e.ic_group))
      dataList.push(e)
    })
    return {data: dataList, total: Number(total[0].total || 0) + Number(total_virtually[0].total || 0)}
  }

  /**
   * 搜索网红
   * @param keyword 
   */
  async search(wx_user: string, keyword: string, skip: number, take: number){
    //认证网红
    let dataList = await this.wxUserRepository.query(`
      select internet_celebrity_group.id,wx_user.name,concern.id as concern_id,wx_user.create_time,wx_user.openid,
        wx_user.avatar_img,wx_user.id_card, internet_celebrity_group.id as ic_group, 'local_ic' as ic_source
      from internet_celebrity_group
      inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
      left join concern on concern.concern_ic_group = internet_celebrity_group.id and concern.wx_user = ?
      where internet_celebrity_group.type = 2 and (wx_user.id_card = ? or wx_user.name like ?) and wx_user.openid in (
        select a.wx_user from user_setting a where a.key = 'overseas' and a.value = 1
      )
      order by wx_user.create_time desc
      limit ?,?
    `,[wx_user, utils.filteremoji(keyword), `%${keyword}%`, skip, take])

    //虚拟网红
    //1、视频库tk ins
    let virtually = await this.wxUserRepository.query(`
      select a.id,
      (
        select name from internet_celebrity where ic_group = a.id
        order by id ASC
        limit 0,1
      ) as name,
      b.id as concern_id,(
      select avatar_img from internet_celebrity where ic_group = a.id
      order by id ASC
      limit 0,1
      ) as avatar_img,a.id_card, a.id as ic_group, 'virtually_ic' as ic_source
      from internet_celebrity_group a
      inner join platform on platform.ic_group = a.id
      left join concern b on b.concern_ic_group = a.id and b.wx_user = ?
      where a.type = 0 and
      (
        a.id in (
          select ic_group from internet_celebrity where name like ?
        ) or a.id_card = ?
      )
      and (
        platform.platform in (select setting.value from setting where setting.key = 'level3')
        or (select count(1) from platform where platform.platform != '' and platform.ic_group = a.id) = 0
      )
        and a.delete_tag = 0 and a.id in (
          select ic_group from video
          where 
          (
            -- 提问视频，进入网红主页
            (
              video.type = 1 and video.original = 0 and video.in_ic = 1
            )
            -- 非认证作品，进入网红主页
            or (
              video.overseas = 3 and video.in_ic = 1
            )
            -- 认证作品
            or (
              video.overseas = 1
            )
            -- 视频库视频
            or (
              video.overseas = 0 and video.type = 0 and (video.in_ic is null or video.in_ic = 1)
            )
          )
        )
      limit ?,?
    `,[wx_user, `%${keyword}%`, utils.filteremoji(keyword), skip, take])

    
    
    //查询平台信息
    let platformList = await this.wxUserRepository.query(`
      select platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
          'virtually_ic_info' as type
          from internet_celebrity_group
          inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
          inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
          inner join platform on platform.ic_group = internet_celebrity_group.id
          where internet_celebrity_group.type = 0 and(internet_celebrity_group.id_card = ? or internet_celebrity.name like ?) and (
            platform.platform in (select setting.value from setting where setting.key = 'level3')
            or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
          )
      union
      select distinct platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
        'local_ic_info' as type
      from wx_user a
      inner join internet_celebrity_group on internet_celebrity_group.wx_user = a.openid and internet_celebrity_group.type = 2
      inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
      inner join platform on platform.ic_group = internet_celebrity_group.id and platform.id = internet_celebrity.platform and platform.platform != '' and platform.platform is not null
      where internet_celebrity_group.type = 2 and a.openid in (
              select a.wx_user from user_setting a where a.key = 'overseas' and a.value = 1
            ) and (a.id_card = ? or a.name like ?)
    `,[utils.filteremoji(keyword), `%${keyword}%`, utils.filteremoji(keyword), `%${keyword}%`])

    dataList.map(e => {
      e.platformList = this.batchPlatform(platformList.filter(c => c.id == e.ic_group))
    })
    virtually.map(e => {
      e.platformList = this.batchPlatform(platformList.filter(c => c.id == e.ic_group))
    })

    virtually.map(e => {
      e.overseas = 3
      dataList.push(e)
    })

    dataList.filter(e => e.openid == wx_user).map(e => {
      e.disabled_concern = true
      delete e.openid
    })
    return dataList
  }

  
  /**
   * 搜索网红
   * @param keyword 
   */
  async search_background(wx_user: string, keyword: string, skip: number, take: number){
    //虚拟网红
    //1、视频库tk ins
    let virtually = await this.wxUserRepository.query(`
      select distinct * from (
        select a.id, a.name,b.id as concern_id,(
        select avatar_img from internet_celebrity where ic_group = a.id
        order by id ASC
        limit 0,1
        ) as avatar_img,a.id_card, a.id as ic_group
        from internet_celebrity_group a
        inner join platform on platform.ic_group = a.id
        left join concern b on b.concern_ic_group = a.id and b.wx_user = ?
        where (
            (
              a.type = 0 and (
                platform.platform in (select setting.value from setting where setting.key = 'level3')
                or (select count(1) from platform where platform.platform != '' and platform.ic_group = a.id) = 0
              )
            )
          ) and (
          a.id_card = ? or a.id in (
            select ic_group from internet_celebrity where LOWER(name) like ?
          )
        )
        and a.id in (
          select ic_group from video
          where 
          (
            -- 提问视频，进入网红主页
            (
              video.type = 1 and video.original = 0 and video.in_ic = 1
            )
            -- 非认证作品，进入网红主页
            or (
              video.overseas = 3 and video.in_ic = 1
            )
            -- 认证作品
            or (
              video.overseas = 1
            )
            -- 视频库视频
            or (
              video.overseas = 0 and video.type = 0 and (video.in_ic is null or video.in_ic = 1)
            )
          )
        )
        order by a.create_time desc
      )a
      limit ?,?
    `,[wx_user, utils.filteremoji(keyword), `%${keyword.toLocaleLowerCase()}%`, skip, take])
    
    let total = await this.wxUserRepository.query(`
      select count(1) as total from (
        select distinct a.id
      from internet_celebrity_group a
      inner join platform on platform.ic_group = a.id
      where (
          (
            a.type = 0 and (
              platform.platform in (select setting.value from setting where setting.key = 'level3')
              or (select count(1) from platform where platform.platform != '' and platform.ic_group = a.id) = 0
            )
          ) 
        ) and (
        a.id_card = ? or a.id in (
          select ic_group from internet_celebrity where LOWER(name) like ?
        )
      )
      and a.id in (
        select ic_group from video
        where 
        (
          -- 提问视频，进入网红主页
          (
            video.type = 1 and video.original = 0 and video.in_ic = 1
          )
          -- 非认证作品，进入网红主页
          or (
            video.overseas = 3 and video.in_ic = 1
          )
          -- 认证作品
          or (
            video.overseas = 1
          )
          -- 视频库视频
          or (
            video.overseas = 0 and video.type = 0 and (video.in_ic is null or video.in_ic = 1)
          )
        )
      )
    )a
    `,[utils.filteremoji(keyword), `%${keyword.toLocaleLowerCase()}%`])

    //查询平台信息
    let platformList = await this.wxUserRepository.query(`
      select distinct platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,
        internet_celebrity.account,internet_celebrity_group.id
      from internet_celebrity_group
      inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
      inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
      inner join platform on platform.ic_group = internet_celebrity_group.id
      where internet_celebrity_group.type = 0 
        and (internet_celebrity_group.id_card = ? or LOWER(internet_celebrity.name) like ?) 
        and (
          platform.platform in (select setting.value from setting where setting.key = 'level3')
          or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
        )
        and(
          (internet_celebrity.name is not null and internet_celebrity.name != '') or
          (internet_celebrity.img is not null and internet_celebrity.img != '') or
          (internet_celebrity.avatar_img is not null and internet_celebrity.avatar_img != '') or
          (internet_celebrity.account is not null and internet_celebrity.account != '')
        )
    `,[utils.filteremoji(keyword), `%${keyword.toLocaleLowerCase()}%`])

    virtually.map(e => {
      e.platformList = this.batchPlatform(platformList.filter(c => c.id == e.ic_group))
    })

    return {data: virtually, total:total[0].total}
  }

  async getVideoOtherParams(ids, findAnswerIds?: any, wx_user?: string){
    if(ids.length === 0){
      return {answerList: [], multiImg: []}
    }
    let sql = []
    ids.map(e => {
      sql.push(` b.video_id = ? `)
    })
    let sqlText = ''
    if(sql.length > 0){
      sqlText = ` and (${sql.join(' or ')})`
    }

    let sqlText_Answer = ''
    if(findAnswerIds){
      let sqlAnswer = []
      findAnswerIds.map(e => {
        sqlAnswer.push(` b.video_id = ? `)
      })
      if(sqlAnswer.length > 0){
        sqlText_Answer = ` and (${sqlAnswer.join(' or ')})`
      }
    }else{
      sqlText_Answer = sqlText 
    }
    let answerList: any  = []
    if(findAnswerIds && findAnswerIds.length === 0){
      answerList = []
    }else{
      answerList = await this.wxUserRepository.query(`
        select b.id,b.video_id,b.wx_user,b.create_time,b.check,b.check_time,b.type,b.answer_template_id
          ,b.id as answer_id,c.use_wx_user,e.platform,e.ic_name,e.img,e.img_id, c.status as profit_status, b.id_card as id_card,b.reject_auto_time
        from answer b
        left join profit as c on c.answer_id = b.id
        left join answer_info as e on e.answer_id = b.id
        where b.delete_tag = 0 ${sqlText_Answer}
        order by e.create_time desc
      `,findAnswerIds || ids)
    }

    let multiImg = await this.wxUserRepository.query(`
      select distinct * from (
        select b.*,multi_img.img as multi_img,b.id as answer_id, '' as use_wx_user,multi_img.cover,multi_img.id as multi_img_id
        from multi_img
        inner join answer as b on b.video_id = multi_img.video_id
        where b.check = 1 and b.wx_user = ? and b.delete_tag = 0 ${sqlText}
        union all
        select b.*,multi_img.img as multi_img,b.id as answer_id,profit.use_wx_user,multi_img.cover,multi_img.id as multi_img_id
        from multi_img
        inner join answer as b on b.video_id = multi_img.video_id
        inner join profit on profit.answer_id = b.id
        where b.check = 1 and profit.use_wx_user = ? ${sqlText}
      )a
      order by a.cover desc,a.multi_img_id asc
    `,[wx_user, ...ids, wx_user, ...ids])

    return {answerList, multiImg}
  }

  
  /**
   * 查询网红信息和视频
   * @param id
   */
  async findInfo(wx_user: string, id?: number, ic_group?: number, unconcern_id?: number): 
    Promise<{info:any, videos: Video[], multiImg: [], answerList: []}>{
    //网红信息
    let info:any = {}
    let videos:Video[] = []
    let answerList: any = []
    let multiImg: any = []
    if(ic_group){
      //判断网红是否是真实网红
      let findAIc = await this.internetCelebrityGroupRepository.findOne({where:{id: ic_group}})
      if(findAIc?.type === 2){
        //查找真实网红的用户id
        let findAId = await this.wxUserRepository.findOne({where:{openid: findAIc.wx_user}})
        if(findAId){
          id = findAId.id
          ic_group = undefined
        }
      }
    }
    //虚拟网红
    if(ic_group){
      info = await this.wxUserRepository.query(`
        select a.id as user_id, b.name,b.img,b.avatar_img,c.id as concern_id,a.id_card, a.type, a.id as ic_group
          ,wx_user.name as wx_user_name,wx_user.id_card as wx_user_id_card
          ,wx_user.avatar_img as wx_avatar_img
        from internet_celebrity_group a
        left join internet_celebrity b on b.ic_group = a.id
        left join concern c on c.concern_ic_group = a.id and c.wx_user = ?
        inner join wx_user on wx_user.openid = a.wx_user
        where a.id = ? and a.delete_tag = 0
        limit 0,1
      `,[wx_user, ic_group])

      info.filter(e => e.type == 2).map(e => {
        e.name = e.wx_user_name
        e.id_card = e.wx_user_id_card
        e.avatar_img = e.wx_avatar_img
      })

      //视频库网红不显示图片
      let { sql, beforeParams, afterParams} = getQueryVideoField(wx_user, `
        (
          select video.*, profit.answer_id as profit_answer_id,answer.wx_user as answer_wx_user,profit.create_time as profit_create_time,
          
          (
            select v.id from video as v
            inner join answer on answer.video_id = v.id
            where v.id = video.id and v.check = 1 and v.ic_group in (
              select internet_celebrity_group.id as ic_group from internet_celebrity_group
              left join video v2 on v2.ic_group = internet_celebrity_group.id
              left join platform on platform.ic_group = internet_celebrity_group.id
              inner join answer on answer.video_id = v2.id
              where (
                (
                  internet_celebrity_group.type = 2 and v2.source != 2
                ) or 
                (
                  internet_celebrity_group.type = 0 and (
                    platform.platform in (select setting.value from setting where setting.key = 'level3')
                    or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                  )
                ) or (
                  internet_celebrity_group.type = 3 and v2.in_ic = 1 and v2.source != 2
                ) or (
                  ((v.overseas = 3 and v2.in_ic = 1) or v.overseas = 1) and v.original = 1
                )
              ) 
              
            ) and answer.check = 1 and answer.delete_tag = 0
          ) as workSource
          from video
          inner join wx_user on wx_user.openid = video.wx_user
          inner join answer on answer.video_id = video.id
          left join profit on profit.answer_id = answer.id and profit.use_wx_user = ?
          where video.ic_group = ? and video.check = 1 and answer.check = 1 
            and 
              (
                -- 提问视频，进入网红主页
                (
                  video.original = 0 and video.in_ic = 1
                )
                -- 非认证作品，进入网红主页
                or (
                  video.overseas = 3 and video.in_ic = 1 and video.profit_type = 1 and video.original = 1 and video.source != 2
                )
                -- 认证作品
                or (
                  video.overseas = 1 and video.profit_type = 1 and video.original = 1 and video.source != 2
                )
                -- 视频库视频
                or (
                  video.overseas = 0 and video.type = 0 and (video.in_ic is null or video.in_ic = 1) and video.original = 1
                    and (
                        video.ic_group in (
                        select platform.ic_group from platform
                        where platform.platform in (select setting.value from setting where setting.key = 'level3')
                      )
                      or (select count(1) from platform where platform.platform != '' and platform.ic_group = video.ic_group) = 0
                    )
                )
              )
            and video.delete_tag = 0
        ) video
        `, undefined, ',video.profit_answer_id,video.answer_wx_user, video.workSource')
      videos = await this.wxUserRepository.query(`
        select 
        ${sql}
          order by video.profit_create_time desc,video.create_time desc
      `, [...beforeParams, wx_user, ic_group, ...afterParams])

      let result = await this.getVideoOtherParams(videos.map(e => e.id), videos.map(e => e.id), wx_user)
      multiImg = result.multiImg
      answerList = result.answerList

      
      videos.filter((e:any) => e.workSource).map((e:any) => {
        e.workSource = 'ic'
      })
      
    }else if (unconcern_id){
      //注销的网红
      info = await this.unConcernRepository.query(`
        select a.id as concern_id,a.name, 'unconcern' as unconcern from unconcern a
        where a.id = ?
      `, [unconcern_id])
    }else if(id){
      //真实网红
      info = await this.wxUserRepository.query(`
        select wx_user.id, wx_user.name, wx_user.avatar_img, concern.id as concern_id, wx_user.id_card, wx_user.openid as wx_user,user_setting.id as isoverseas
        from wx_user
        left join user_setting on user_setting.wx_user = wx_user.openid and user_setting.key = 'overseas' and user_setting.value = 1
        left join concern on concern.concern_wx_user_id = wx_user.id and concern.wx_user = ?
        where wx_user.id = ?
      `,[wx_user, id])
      if(info.length > 0 && info[0].wx_user !== system_wx_user && info[0].wx_user !== system_wx_user_2 && !info[0].isoverseas){
        info = []
      }
      if(info.length > 0 && info[0].wx_user == wx_user){
        info[0].author = true
      }
      
      //视频库网红不显示图片
      let { sql, beforeParams, afterParams} = getQueryVideoField(wx_user, `
        (
          select video.*, profit.answer_id as profit_answer_id,answer.wx_user as answer_wx_user,profit.create_time as profit_create_time
          from video
          inner join wx_user on wx_user.openid = video.wx_user
          inner join answer on answer.video_id = video.id
          left join profit on profit.answer_id = answer.id and profit.use_wx_user = ?
          where video.wx_user = ? and video.check = 1 and answer.check = 1 
            and video.overseas = 1 and video.profit_type = 1 and video.original = 1
            and video.delete_tag = 0
        ) video
        `, undefined, ',video.profit_answer_id,video.answer_wx_user')
      if(info.length > 0){
        videos = await this.wxUserRepository.query(`
          select 
          ${sql}
            order by video.profit_create_time desc,video.create_time desc
        `, [...beforeParams, wx_user, info[0].wx_user, ...afterParams])
      }

      let result = await this.getVideoOtherParams(videos.map(e => e.id), videos.map(e => e.id), wx_user)
      multiImg = result.multiImg
      answerList = result.answerList
      
      videos.map((e:any) => {
        e.workSource = 'ic'
      })
    }
    //查询平台信息
    if(info.length > 0){
      let platformList = []
      if(ic_group){
        platformList = await this.wxUserRepository.query(`
          select platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
            'virtually_ic_info' as type
            from internet_celebrity_group
            inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
            inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
            inner join platform on platform.ic_group = internet_celebrity_group.id
            where internet_celebrity_group.id = ?
        `,[ic_group])
        info[0].platformList = this.batchPlatform(platformList)
      }else{
        platformList = await this.wxUserRepository.query(`
          select distinct platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
            'local_ic_info' as type
          from wx_user a
          inner join internet_celebrity_group on internet_celebrity_group.wx_user = a.openid and internet_celebrity_group.type = 2
          inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
          inner join platform on platform.ic_group = internet_celebrity_group.id and platform.id = internet_celebrity.platform
          where internet_celebrity_group.wx_user = ? and internet_celebrity_group.type = 2
            and a.openid in (
              select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = 1
            )
        `,[info[0].wx_user])
        info[0].platformList = this.batchPlatform(platformList)
      }
    }

    videos.filter((e:any) => e.answer_wx_user == wx_user && !e.profit_answer_id).map((e:any) => {
      e.profit_answer_id = true
    })

    //网红下所有视频
    return {info:info[0],videos, multiImg, answerList}
  }


  /**
   * 查询关注网红id
   * @param wx_user 
   * @param id 
   * @param ic_group 
   * @param unconcern_id 
   * @returns 
   */
  async findConcernInfo(wx_user: string, id: number, ic_group: number, unconcern_id){
    if(ic_group){
      let findConcern = await this.wxUserRepository.query(`
        select concern.id as concern_id, wx_user.id
        from internet_celebrity_group
        inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
        left join concern on internet_celebrity_group.id = concern.concern_ic_group
        where internet_celebrity_group.id = ? and concern.wx_user = ? and internet_celebrity_group.type = 2
      `,[ic_group, wx_user])

      if(findConcern.length > 0){
        return findConcern[0]
      }else{
        findConcern = await this.wxUserRepository.query(`
          select concern.id as concern_id, internet_celebrity_group.id as ic_group 
          from internet_celebrity_group
          left join concern on internet_celebrity_group.id = concern.concern_ic_group
          where internet_celebrity_group.id = ? and concern.wx_user = ? and internet_celebrity_group.type != 2
        `,[ic_group, wx_user])
        return findConcern[0]
      }
    }else if(id){
      let findConcern = await this.wxUserRepository.query(`
        select concern.id as concern_id, wx_user.id
        from wx_user
        left join concern on concern.concern_wx_user_id = wx_user.id
        where wx_user.id = ? and concern.wx_user = ?
      `,[id, wx_user])
      return findConcern[0]
    }else if(unconcern_id){
      //注销的网红
      let findConcern = await this.unConcernRepository.query(`
        select a.id as concern_id,a.name, 'unconcern' as unconcern from unconcern a
        where a.id = ?
      `, [unconcern_id])
      return findConcern[0]
    }
  }

  async findIcInfo(wx_user: string, id: number, ic_group: number) {
    let icInfo
    if(ic_group){
      //真实网红
      let findConcern = await this.wxUserRepository.query(`
        select 
          wx_user.id, 
          wx_user.name, 
          wx_user.id_card,
          wx_user.avatar_img, 
          wx_user.openid as wx_user
        from internet_celebrity_group
        inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
        where internet_celebrity_group.type = 2 and internet_celebrity_group.id = ?
      `,[ic_group])

      if(findConcern.length > 0){
        if(findConcern[0].wx_user == wx_user){
          findConcern[0].author = true
        }
        icInfo = findConcern[0]
      }else{
        //虚拟网红
        let findConcern = await this.wxUserRepository.query(`
          select 
            a.id as ic_group,
            b.name,
            a.id_card, 
            b.avatar_img,
            a.wx_user
          from internet_celebrity_group a
          inner join internet_celebrity b on b.ic_group = a.id
          where a.id = ?
          limit 0,1
        `,[ic_group])
        icInfo = findConcern[0]
      }
    }else if(id){
      let findConcern = await this.wxUserRepository.query(`
        select 
          wx_user.id, 
          wx_user.name, 
          wx_user.avatar_img, 
          wx_user.id_card, 
          wx_user.openid as wx_user
        from wx_user
        inner join user_setting on user_setting.wx_user = wx_user.openid and user_setting.key = 'overseas' and user_setting.value = 1
        inner join internet_celebrity_group on internet_celebrity_group.wx_user = wx_user.openid and internet_celebrity_group.type = 2
        where wx_user.id = ?
      `,[id])
      if(findConcern.length > 0){
        if(findConcern[0].wx_user == wx_user){
          findConcern[0].author = true
        }
      }
      icInfo = findConcern[0]
    }
    if(icInfo){
      delete icInfo.wx_user
    }
    return icInfo    
  }

  async findIcInfo2(wx_user: string, id: number, ic_group?: number, unconcern_id?: number) {
    let info
    let platformList = []
    if(ic_group){
      let findAIc = await this.internetCelebrityGroupRepository.query(`
        select 
          internet_celebrity_group.id as user_id, wx_user.name, wx_user.id_card, wx_user.avatar_img, c.id as concern_id,
          internet_celebrity_group.id as ic_group, 'local' as type, internet_celebrity_group.wx_user
        from internet_celebrity_group
        inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
        left join concern c on c.concern_ic_group = internet_celebrity_group.id and c.wx_user = ?
        where internet_celebrity_group.type = 2 and internet_celebrity_group.id = ?
      `,[wx_user, ic_group])
      if(findAIc.length > 0){
        info = findAIc[0]
      }
    }
    //虚拟网红
    if(!info && ic_group){
      info = await this.wxUserRepository.query(`
        select a.id as user_id, b.name,b.img,b.avatar_img,c.id as concern_id,a.id_card, a.id as ic_group, b.account, 'virtual' as type
        from internet_celebrity_group a
        left join internet_celebrity b on b.ic_group = a.id
        left join concern c on c.concern_ic_group = a.id and c.wx_user = ?
        where a.id = ? and a.delete_tag = 0
        limit 0,1
      `,[wx_user, ic_group])
    }else if (!info && unconcern_id){
      //注销的网红
      info = await this.unConcernRepository.query(`
        select a.id as concern_id,a.name, 'unconcern' as unconcern from unconcern a
        where a.id = ?
      `, [unconcern_id])
    }else if(!info && id){
      //真实网红
      info = await this.wxUserRepository.query(`
        select 
          wx_user.id, wx_user.name, wx_user.avatar_img, concern.id as concern_id, wx_user.id_card, wx_user.openid as wx_user,user_setting.id as isoverseas,
          internet_celebrity_group.id as ic_group, 'local' as type
        from wx_user
        left join user_setting on user_setting.wx_user = wx_user.openid and user_setting.key = 'overseas' and user_setting.value = 1
        left join concern on concern.concern_wx_user_id = wx_user.id and concern.wx_user = ?
        inner join internet_celebrity_group on internet_celebrity_group.wx_user = wx_user.openid and internet_celebrity_group.type = 2
        where wx_user.id = ?
      `,[wx_user, id])
      if(info.length > 0 && info[0].wx_user !== system_wx_user && info[0].wx_user !== system_wx_user_2 && !info[0].isoverseas){
        info = []
      }
      if(info.length > 0 && info[0].wx_user == wx_user){
        info[0].author = true
      }
    }
    if(info.length > 0){
      let icInfo = info[0]
      if(icInfo.unconcern !== 'unconcern'){
        if(icInfo.type === 'local'){
          let local = await this.internetCelebrityGroupRepository.query(`
            select count(1) as total from video
            where video.wx_user = ? and video.profit_type = 1 and video.original = 1
          `,[icInfo.wx_user])
          if(local[0].total == 0){
            icInfo.platform_count = 0
          }
          
          
        }else if(icInfo.type === 'virtual'){
          let virtual = await this.internetCelebrityGroupRepository.query(`
            select count(1) as total from video as v
            inner join internet_celebrity_group as icg on icg.id = v.ic_group
            where v.ic_group = ? and (
              (
                icg.type = 0 and (
                  v.ic_group in (select ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3')
                  or (select count(1) from platform where platform.platform != '' and platform.ic_group = icg.id) = 0
                )
              )
              or (
                (icg.type = 3 or icg.type = 2)
                and v.source != 2
              )
              or (
                icg.type = 0 and v.overseas = 3 and v.original = 1
              )
            )
            and icg.delete_tag = 0
            and 
              (
                -- 提问视频，进入网红主页
                (
                  v.type = 0 and v.original = 0 and v.in_ic = 1
                )
                -- 非认证作品，进入网红主页
                or (
                  v.overseas = 3 and v.profit_type = 1
                )
                -- 认证作品，看完整版
                or (
                  v.overseas = 1 and v.profit_type = 1
                )
                -- 视频库视频
                or (
                  v.overseas = 0 and v.type = 0 and (v.in_ic = 1 or v.in_ic is null)
                )
              )
          `,[icInfo.ic_group])
          if(virtual[0].total == 0){
            icInfo.platform_count = 0
            delete icInfo.id_card
          }

          
        }
        if(icInfo.platform_count !== 0){
          let findPlatform = await this.internetCelebrityGroupRepository.query(`
            select count(1) from internet_celebrity
            where internet_celebrity.ic_group = ? and (
              (internet_celebrity.account is not null and internet_celebrity.account != '')
              or (internet_celebrity.avatar_img is not null and internet_celebrity.avatar_img is not null != '')
              or (internet_celebrity.name is not null and internet_celebrity.name is not null != '')
              or (internet_celebrity.img is not null and internet_celebrity.img is not null != '')
              or internet_celebrity.platform is not null
            )
          `, [icInfo.ic_group])
          if(findPlatform.length > 0){
            icInfo.platform_count = 1
          }
        }


       
      }
      if(icInfo.platform_count == undefined){
        if(icInfo.platform || icInfo.account || icInfo.avatar_img || icInfo.name || icInfo.img){
          icInfo.platform_count = 1
        }
      }
      delete icInfo.account
      delete icInfo.type
      for(let key in icInfo){
        if(utils.validIsNull(icInfo[key])){
          delete icInfo[key]
        }
      }
      return {icInfo,platformList}
    }else{
      return undefined
    }
  }

  async findIcPlatform(ic_group: number, id: number){
    if(id){
      let platformList = await this.wxUserRepository.query(`
        select distinct platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
          'local_ic_info' as type
        from wx_user a
        inner join internet_celebrity_group on internet_celebrity_group.wx_user = a.openid and internet_celebrity_group.type = 2
        inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
        inner join platform on platform.ic_group = internet_celebrity_group.id and platform.id = internet_celebrity.platform
        where a.id = ? and internet_celebrity_group.type = 2
          and a.openid in (
            select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = 1
          )
      `,[id])
      return this.batchPlatform(platformList)
    }else if(ic_group){
      let platformList = await this.wxUserRepository.query(`
        select platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
          'virtually_ic_info' as type
          from internet_celebrity_group
          inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
          inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
          inner join platform on platform.ic_group = internet_celebrity_group.id
          where internet_celebrity_group.id = ?
      `,[ic_group])
      return this.batchPlatform(platformList)
    }
  }


  
  /**
   * 用户是否存在
   */
   async isExists(wx_user: string, account: number): Promise<any> {
    let info = await this.wxUserRepository.query(`
      select d.id, 1 as overseas, d.openid
      from wx_user d
      inner join internet_celebrity_group on internet_celebrity_group.wx_user = d.openid and internet_celebrity_group.type = 2
      inner join video on video.wx_user = d.openid and video.profit_type = 1 and video.check = 1 and video.original = 1 and video.overseas = 1
      where d.id_card = ? and d.openid in (
        select a.wx_user from user_setting a where a.key = 'overseas' and a.value = 1 and a.wx_user = d.openid
      )
      union
      select internet_celebrity_group.id, 3 as overseas, '' openid
      from internet_celebrity_group
      inner join platform on platform.ic_group = internet_celebrity_group.id
      where internet_celebrity_group.id_card = ? 
        and (
          (
            internet_celebrity_group.type = 0 and (
              platform.platform in (select setting.value from setting where setting.key = 'level3')
              or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
            )
          )
          or internet_celebrity_group.type = 3 or internet_celebrity_group.type = 2
        )
        and internet_celebrity_group.delete_tag = 0 and internet_celebrity_group.id in (
          select ic_group from video
          where 
          (
            -- 提问视频，进入网红主页
            (
              video.original = 0 and video.in_ic = 1
            )
            -- 非认证作品，进入网红主页
            or (
              video.overseas = 3 and video.in_ic = 1 and video.profit_type = 1 and video.original = 1
            )
            -- 认证作品
            or (
              video.overseas = 1 and video.profit_type = 1 and video.original = 1
            )
            -- 视频库视频
            or (
              video.overseas = 0 and video.type = 0 and (video.in_ic is null or video.in_ic = 1) and video.original = 1
            )
          )
        )
    `, [account, account])

    if(info.length === 0){
      return {exists:false,message:'该用户不存在'}
    }else{
      if(info[0].openid == wx_user) {
        return {exists:false,message:'你不能关注自己'}
      }else{
        let platformList = []
        //查询平台信息
        if(info.length > 0 && info[0].unconcern !== 'unconcern'){
          if(info[0].overseas == 1){
            platformList = await this.wxUserRepository.query(`
              select distinct platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
                'local_ic_info' as type
              from wx_user a
              inner join internet_celebrity_group on internet_celebrity_group.wx_user = a.openid and internet_celebrity_group.type = 2
              inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
              inner join platform on platform.ic_group = internet_celebrity_group.id and platform.id = internet_celebrity.platform
              where a.id = ?
                and a.openid in (
                  select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = 1
                )
            `,[info[0].id])
          }else{
            platformList = await this.wxUserRepository.query(`
              select distinct platform.platform,internet_celebrity.name as ic_name,internet_celebrity.img,internet_celebrity.avatar_img,internet_celebrity.account,internet_celebrity_group.id,
                  'virtually_ic_info' as type
              from internet_celebrity_group 
              inner join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
              inner join platform on platform.ic_group = internet_celebrity_group.id and platform.id = internet_celebrity.platform
              where internet_celebrity_group.id = ?
                and (
                  (
                    internet_celebrity_group.type = 0 and (
                      platform.platform in (select setting.value from setting where setting.key = 'level3')
                      or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                    )
                  )
                  or internet_celebrity_group.type = 3
                )
            `,[info[0].id])
          }
        }
        platformList = this.batchPlatform(platformList)
        return {exists:true, overseas: info[0].overseas || info[1].overseas, id: info[0].id, platformList}
      }
    }
  }



  /**
   * 获取用户阿里账户信息
   * @param openid 
   * @returns 
   */
  get_alipay_account(openid: string): Promise<WxUser>{
    return this.wxUserRepository.findOne({where:{openid:openid}})
  }

  /**
   * 修改用户的支付宝账户
   * @param openid 
   * @param alipay_account 
   * @param alipay_account_name 
   * @returns 
   */
  update_alipay_account(openid: string, alipay_account: string, alipay_account_name: string): Promise<UpdateResult>{
    return this.wxUserRepository.update({openid:openid},{alipay_account:alipay_account,alipay_account_name:alipay_account_name})
  }

  findOne_By_wx_user_key(id: number): Promise<WxUser> {
    return this.wxUserRepository.findOne({where:{id}});
  }

  findAll(): Promise<WxUser[]> {
    return this.wxUserRepository.find();
  }

  async findOne_By_LoginCode(appid: string, login_code: string): Promise<WxUser> {
    let userInfo = await this.wxUserRepository.query(`
      select 
        a.id,
        a.name,
        a.initname,
        a.phone,
        a.wx,
        a.wx_user_key,
        a.openid,
        a.create_time,
        a.wallet_balance,
        a.wallet_balance_history,
        a.wallet_balance_update_time,
        a.countryCode,
        a.alipay_account,
        a.alipay_account_name,
        a.withdrawing,
        b.openid as wx_app_openid,
        a.login_code,
        a.id_card
      from wx_user a
      left join wx_user_openid b on b.unionid = a.openid
      where a.login_code = ?
    `,[login_code])

    if(userInfo.length > 0){
      let findOverseas = await this.userSettingRepository.findOne({where:{key: 'overseas', wx_user: login_code}})
      let overseas = false //false 非认证 true 认证
      if(findOverseas){
        overseas = findOverseas.value == '0' ? false : true
      }
      if(!overseas){
        userInfo[0].name = userInfo[0].initname
      }
      delete userInfo[0].initname
    }
    return userInfo
  }


  async findOne_By_OpenId(appid: string, openid: string): Promise<WxUser> {
    let userInfo = await this.wxUserRepository.query(`
      select 
        a.id,
        a.name,
        a.initname,
        a.phone,
        a.wx,
        a.wx_user_key,
        a.openid,
        a.create_time,
        a.wallet_balance,
        a.wallet_balance_history,
        a.wallet_balance_update_time,
        a.countryCode,
        a.alipay_account,
        a.alipay_account_name,
        a.withdrawing,
        b.openid as wx_app_openid,
        a.login_code
      from wx_user a
      left join wx_user_openid b on b.unionid = a.openid and b.appid = ?
      where a.openid = ?
    `,[appid, openid])

    if(userInfo.length > 0){
      let findOverseas = await this.userSettingRepository.findOne({where:{key: 'overseas', wx_user: openid}})
      let overseas = false //false 非认证 true 认证
      if(findOverseas){
        overseas = findOverseas.value == '0' ? false : true
      }
      if(!overseas){
        userInfo[0].name = userInfo[0].initname
      }
      delete userInfo[0].initname
    }
    return userInfo

    // return this.wxUserRepository.findOne({where:{openid}});
  }

  async findOne_By_Phone(appid: string, phone: string): Promise<WxUser> {
    let userInfo = await this.wxUserRepository.query(`
      select 
        a.id,
        a.name,
        a.initname,
        a.phone,
        a.wx,
        a.wx_user_key,
        a.openid,
        a.create_time,
        a.wallet_balance,
        a.wallet_balance_history,
        a.wallet_balance_update_time,
        a.countryCode,
        a.alipay_account,
        a.alipay_account_name,
        a.withdrawing,
        b.openid as wx_app_openid 
      from wx_user a
      inner join wx_user_openid b on b.unionid = a.openid
      where a.phone = ?
    `,[phone])

    if(userInfo.length > 0){
      let findOverseas = await this.userSettingRepository.findOne({where:{key: 'overseas', wx_user: userInfo[0].openid}})
      let overseas = false //false 非认证 true 认证
      if(findOverseas){
        overseas = findOverseas.value == '0' ? false : true
      }
      if(!overseas){
        userInfo[0].name = userInfo[0].initname
      }
      delete userInfo[0].initname
    }
    return userInfo
  }

  findOne(id: number): Promise<WxUser> {
    return this.wxUserRepository.findOne({where:{id}});
  }

  async remove(id: number): Promise<void> {
    await this.wxUserRepository.delete(id);
  }

  remove_by_user(wx_user: string): Promise<void> {
    return this.wxUserRepository.query(`
      delete wx_user,video,shield,wx_like_video,answer from wx_user
      left join video on video.wx_user = wx_user.openid
      left join shield on shield.wx_user = wx_user.openid
      left join wx_like_video on wx_like_video.wx_user = wx_user.openid
      left join answer on answer.wx_user = wx_user.openid
      where wx_user.openid = ?
    `,[wx_user])
  }

  getIDCard(){
    let id = ''
    let loop = async () => {
      id = utils.randomNumberID(6)
      if(await this.wxUserRepository.findOne({where:{id_card: id}})){
        loop()
      }
    }
    loop()
    return id
  }

  async create(wxUser: WxUser): Promise<WxUser> {
    wxUser.initname = wxUser.name
    // wxUser.id_card = this.getIDCard()
    return await this.wxUserRepository.save(wxUser);
  }

  async update(wxUser: WxUser): Promise<WxUser> {
    return await this.wxUserRepository.save(wxUser);
  }


  findByWxUser(wx_user: string): Promise<WxUser> {
    return this.wxUserRepository.findOne({where:{openid:wx_user}});
  }

  /**
   * 修改手机号
   * @param openid
   * @param phoneNumber
   * @param countryCode
   * @returns
   */
  changePhone(openid: string, phoneNumber: string, countryCode: number): Promise<UpdateResult> {
    return this.wxUserRepository.update({openid:openid},{phone:phoneNumber,countryCode:countryCode});
  }

  async findUserInfo(wx_user: string): Promise<WxUser> {
    let userInfo = await this.wxUserRepository.query(`
      select id,name,avatar_img,initname,id_card from wx_user
      where openid = ?
    `,[wx_user])
    if(userInfo.length > 0){
      userInfo = userInfo[0]
      if(userInfo.name === userInfo.initname){
        userInfo.name_is_init = true
      }
      let findOverseas = await this.userSettingRepository.findOne({where:{key: 'overseas', wx_user: wx_user}})
      let overseas = false //false 非认证 true 认证
      if(findOverseas){
        overseas = findOverseas.value == '0' ? false : true
      }
      if(!overseas){
        userInfo.name = userInfo.initname
      }
      delete userInfo.initname
    }else{
      userInfo = undefined
    }
    return userInfo
  }

  /**
   * 修改名字
   * @param name 
   * @param wx_user 
   * @returns 
   */
  async rename(name: string, wx_user: string): Promise<number> {
    let findId = await this.wxUserRepository.findOne({where:{openid: wx_user}})
    if(findId){
      let res = await this.wxUserRepository.update({openid:wx_user},{name: name})
      console.log(res,'res')
      if(res.affected > 0){
        await this.redisCacheService.del(`icinfo:wxuser:${findId.id}:info`)
      }
      return res.affected
    }else{
      return 0
    }
  }

  async updateAvatarImg(avatar_img: string, avatar_img_id: string, wx_user: string): Promise<UpdateResult> {
    //删除现在的图片
    let findImgId:WxUser = await this.wxUserRepository.findOne({where:{openid:wx_user}})
    if(findImgId?.avatar_img_id){
      await utils.deleteYunRes(findImgId.avatar_img_id, video_SubAppId_List.otherImg)
    }
    let res = await this.wxUserRepository.update({openid:wx_user},{avatar_img: avatar_img, avatar_img_id: avatar_img_id})
    await this.redisCacheService.del(`icinfo:wxuser:${findImgId.id}:info`)
    return res
  }

  
  /**
   * 创建一个用户关联
   * @param appid 
   * @param unionid 
   * @param openid 
   * @returns 
   */
  createOpenIdRela(appid: string, unionid: string, openid: string): Promise<WxUserOpenId>{
    let wxUserOpenid = new WxUserOpenId()
    wxUserOpenid.appid = appid
    wxUserOpenid.unionid = unionid
    wxUserOpenid.openid = openid
    wxUserOpenid.create_time = new Date()
    return this.wxUserOpenIdRepository.save(wxUserOpenid)
  }

  
  /**
   * 查询用户openid
   * @param appid 
   * @param unionid 
   * @returns 
   */
  findOpenId(appid: string, unionid: string): Promise<WxUserOpenId>{
    return this.wxUserOpenIdRepository.findOne({where:{
      appid:appid,
      unionid:unionid
    }})
  }

  phoneLogin(phone: string, validCode: string, wx_user?: string){
    
    return new Promise(async (resolve,reject) => {
      //验证验证码是否正确
      if(!await SMS.validCode(phone, validCode)){
        reject('验证码错误，请检查')
        return
      }
      let save = (id, openid, phone, name, session_key, resolve) => {
        let returnData = {
          id:id,
          phone:phone,
          wx_user:openid,
          name:name,
          session_key:session_key,
        }
        resolve(returnData)
      }
      
      let openid = wx_user || utils.randomString(40)
      let result = {
        openid: openid,
        session_key: '',
        phone: phone
      }
      if(result.openid){
        let wxUser = new WxUser()
        wxUser.create_time = new Date()
        wxUser.openid = result.openid
        wxUser.phone = result.phone
        let wxInfo:WxUser = await this.findOne_By_Phone(wx_appid,result.phone)
        wxInfo = wxInfo[0]
        if(!wxInfo){
          wxUser.name = utils.randomName()
          let wxInfo = await this.create(wxUser)
          let userOpenId = await this.createOpenIdRela(wx_appid, wxInfo.openid, result.openid)
          if(userOpenId && wxInfo){
            save(wxInfo.id, wxInfo.openid, wxInfo.phone,wxInfo.name, result.session_key, resolve)
          }else{
            reject('用户授权失败，保存 openid 失败')
          }
        }else if(wxInfo?.id){
          save(wxInfo.id, wxInfo.openid, wxInfo.phone, wxInfo.name, result.session_key, resolve)
        }else{
          reject('用户授权失败，获取 openid 失败')
        }
      }else{
        reject('用户授权失败')
      }
    })
  }

  async findVideos(wx_user: string, id: number, ic_group: number){
    let videos = []
    //虚拟网红
    if(ic_group){
      videos = await this.wxUserRepository.query(`
        select 
          video.id, 
          profit.answer_id as profit_answer_id,
          answer.wx_user as answer_wx_user
        from video
        inner join wx_user on wx_user.openid = video.wx_user
        inner join answer on answer.video_id = video.id
        left join profit on profit.answer_id = answer.id and profit.use_wx_user = ?
        where video.ic_group = ? and video.check = 1 and answer.check = 1 
          and 
            (
              -- 提问视频，进入网红主页
              (
                video.original = 0 and video.in_ic = 1
              )
              -- 非认证作品，进入网红主页
              or (
                video.overseas = 3 and video.in_ic = 1 and video.profit_type = 1 and video.original = 1 and video.source != 2
              )
              -- 认证作品
              or (
                video.overseas = 1 and video.profit_type = 1 and video.original = 1 and video.source != 2
              )
              -- 视频库视频
              or (
                video.overseas = 0 and video.type = 0 and (video.in_ic is null or video.in_ic = 1) and video.original = 1
                  and (
                      video.ic_group in (
                      select platform.ic_group from platform
                      where platform.platform in (select setting.value from setting where setting.key = 'level3')
                    )
                    or (select count(1) from platform where platform.platform != '' and platform.ic_group = video.ic_group) = 0
                  )
              )
            )
          and video.delete_tag = 0
          order by profit.create_time desc,video.create_time desc
      `, [wx_user, ic_group])
    }else if(id){
      videos = await this.wxUserRepository.query(`
        select 
          video.id, 
          profit.answer_id as profit_answer_id,
          answer.wx_user as answer_wx_user
        from video
        inner join wx_user on wx_user.openid = video.wx_user
        inner join answer on answer.video_id = video.id
        left join profit on profit.answer_id = answer.id and profit.use_wx_user = ?
        where wx_user.id = ? and video.check = 1 and answer.check = 1 
          and video.overseas = 1 and video.profit_type = 1 and video.original = 1
          and video.delete_tag = 0
        order by profit.create_time desc,video.create_time desc
      `, [wx_user, id])
    }

    videos.filter((e:any) => e.answer_wx_user == wx_user && !e.profit_answer_id).map((e:any) => {
      e.profit_answer_id = 1
    })
    videos.map(e => {
      delete e.answer_wx_user
    })
    return videos
  }

  async findVideosInfo(wx_user: string, basic: number[], collection: number[], profit: number[]){
    let videos = []
    let multiImg = []
    let platformList = []
    let answerList = []

    let basics = await this.wxUserRepository.find({where:{id: In(basic)}})
   
    let result = await this.getVideoOtherParams(videos.map(e => e.id), videos.map(e => e.id), wx_user)
    multiImg = result.multiImg
    answerList = result.answerList


    //查询视频
    return { videos, platformList, multiImg, answerList }
  }
  clearConcern(wx_user:string){
    return this.wxUserRepository.update({openid: wx_user}, {concern_is_update: 0})
  }

  /**
   * 根据视频编号 查询收藏数据
   * @param video_ids 
   * @param wx_user 
   * @returns 
   */
  findCollections_ByIds(video_ids: number[], wx_user: string){
    let ids = []
    video_ids.map(e => {
      ids.push(` lv.video_id = ? `)
    })
    return this.wxUserRepository.query(`
      select lv.video_id from wx_like_video as lv 
      where lv.wx_user = ? and lv.delete_tag = 0 and (${ids.join(' or ')})
    `,[wx_user, ...video_ids])
  }
}
